import type { RequestConfig } from '@umijs/max';
import { message } from 'antd';
import { getAuthElement } from './services/demo/UserController';
// 运行时配置
const _projectname = 'auth';
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState() {
  const { result } = await getAuthElement("934");
  const elements = result.elements.map((element: { code: string; }) => element.code);
  return {
    name: 'Thinkcar_子应用初始状态',
    projectname: _projectname,
    elements
  };
}

export const layout = () => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
    },
    layout: 'top',
  };
};



export const qiankun = {
  // 应用加载之前
  async bootstrap(props: any) {
    console.log('===auth bootstrap', props);
  },
  // 应用 render 之前触发
  async mount(props: any) {
    console.log('auth mount', props);
  },
  // 应用卸载之后触发
  async unmount(props: any) {
    console.log('auth unmount', props);
  },
};

export const request: RequestConfig = {
  timeout: 10000,
  // other axios options you want
  errorConfig: {
    errorHandler(err) {
      console.log(err);

    },
    errorThrower(err) {
      // message.error(err.appMesg);
      console.log(err);

    }
  },
  requestInterceptors: [
    // 直接写一个 function，作为拦截器
    (url, options) => {      
      if (process.env.NODE_ENV === "production") {
        localStorage.getItem('tc_all_token') && (options.headers!.token = localStorage.getItem('tc_all_token') || "");
      } else {
        options.headers!.token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIzMDMiLCJjb2RlIjoiMTY2MjA5NjU3MTMiLCJuYW1lIjoiamluY2FueXVAdGhpbmtjYXIuY29tIiwidGltZSI6MTcxNTA4MTE4OTAzMywiZXhwIjoxNzE3NjczMTg5fQ.JA8zy0weA4kLOZhwEABWpB16Wrry53a432Vo1clYftob8wX0H1qEKWJ4KDCZNgnBCmZDswwhi3Tb9OCKT2nq-6stboJIPMRS8S9DqbbfuwST210fh639Hd_6QOpSljeR5MwA8kfbZ3KbOueBsEK0J5lufTHViTtJ_P708sqYJCg";
      }
      // do something
      return { url, options };
    },
    // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
    [(url, options) => { return { url, options }; }, (error) => { return Promise.reject(error); }],
    // 数组，省略错误处理
    [(url, options) => { return { url, options }; }]
  ],
  responseInterceptors: [// 直接写一个 function，作为拦截器
    (response: any) => {
      // 不再需要异步处理读取返回体内容，可直接在data中读出，部分字段可在 config 中找到
      const { data = {} as any, config } = response;
      // return response;
      // do something
      if (!data.success) {
        message.error(data.appMesg);
      }
      return response;

    },
    // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
    [(response) => { return response; }, (error) => { return Promise.reject(error); }],
    // 数组，省略错误处理
    [(response) => { return response; }]]
};
export function onRouteChange({ routes, matchedRoutes, location, action }: any) {
  if (action == 'POP') {
    // const _pn = _projectname
    if (location.pathname != '/' + _projectname && location.pathname != '/' + _projectname+'/home' && location.pathname != '/') {
      console.log('===============onRouteChange== 2333333==',location);
      const _runame = location.pathname.replace('/' + _projectname, '');
      let _fp: any;
      for (let _rkey in routes) {
        if (routes.hasOwnProperty(_rkey)) { // 确保key是obj自身的属性，而不是从原型链上继承的
          console.log(_rkey, routes[_rkey]);
          if (routes[_rkey].path == _runame) {
            _fp = routes[_rkey];
          }
        }
      }
      if (_fp) {
        const _hmenu = JSON.parse(localStorage.getItem(_projectname + 'HistoryMenu')!) || [];
        let _hl = [] as any[];

        if (_hmenu.length) {
          _hl = _hmenu.filter((_item: any) => _item.id != _fp.id);
          _hl.unshift(_fp);
        } else {
          _hl.push(_fp);
        }
        localStorage.setItem(
          _projectname + 'HistoryMenu',
          JSON.stringify(_hl)
        );
      }

      // console.log(routes); //路由集合
      // console.log(matchedRoutes); //当前匹配的路由及其子路由
      // console.log(location); //location及其参数
      // console.log(action); //当前跳转执行的操作
      // console.log('===============onRouteChange==end==');
    }
  }
}